package com.hhf.rpc.core;

import org.junit.Test;

import java.util.concurrent.TimeUnit;

/**
 * @Author hhf
 * @Date 2024/10/15
 * @Description
 */

public class RpcCoreMain {

    private static volatile boolean flag = true;
//    private static boolean flag = true;

    /**
     * 由于现代的处理器和JVM会进行一些调优,使得不加volatile也能正常运行
     * 虽然但是,建议还是添加volatile关键词
     * @throws InterruptedException
     */
    @Test
    public void VolatileTest() throws InterruptedException {

        Thread t1 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t------come in");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            flag = false;
        }, "t1");

        Thread t2 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t------come in");
            try {
                TimeUnit.SECONDS.sleep(2);
                while (flag) {

                }
                System.out.println(Thread.currentThread().getName() + "\t------flag被设置成false,程序结束");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t2");

        t1.start();
        t2.start();

        //解决程序未运行完就结束进程
        t1.join();
        t2.join();

    }
}
